import React, { Component } from 'react'
import PropTypes from 'prop-types'
// import GoodsName from './components/GoodsName'
// import GoodsContent from './components/GoodsContent'
import axios from 'axios'

const GoodsName = (props) => {
  const { goodsList, tabIndex, handleNameClick } = props
  return (
    <>
      {goodsList.map((item, index) => {
        return (
          <div key={item.name}>
            <h2
              className={tabIndex === index ? 'active' : ''}
              onClick={() => {
                handleNameClick && handleNameClick(item.children)
              }}
            >
              {item.name}
            </h2>
          </div>
        )
      })}
    </>
  )
}

GoodsName.defaultProps = {
  tabIndex: 0,
}

GoodsName.propTypes = {
  tabIndex: PropTypes.string,
  handleNameClick: PropTypes.func,
}

const GoodsContent = (props) => {
  const { contentList, handleRemoveClick } = props
  return (
    <>
      {contentList.map((item, index) => {
        return (
          <ul>
            <li
              onClick={() => {
                handleRemoveClick && handleRemoveClick(index)
              }}
            >
              {item.name}
            </li>
          </ul>
        )
      })}
    </>
  )
}

export default class index extends Component {
  state = {
    goodsList: [],
    contentList: [],
    tabIndex: 0,
  }
  async fetchGoodsList() {
    const result = await axios.get('/data.json')
    console.log('result:', result.data)
    this.setState({ goodsList: result.data })
  }

  componentDidMount() {
    this.fetchGoodsList()
  }

  handleRemoveClick = (index) => {
    // splice 操作数组，会返回一个新数组，同时会改变原数组
    let copyList = [...this.state.contentList]
    copyList.splice(index, 1)
    this.setState({ contentList: copyList })
  }

  handleNameClick = (arr) => {
    this.setState({
      contentList: arr,
    })
  }

  render() {
    const { goodsList, contentList, tabIndex } = this.state
    return (
      <div>
        <GoodsName
          goodsList={goodsList}
          tabIndex={tabIndex}
          handleNameClick={(arr) => {
            this.handleNameClick(arr)
          }}
        />
        <GoodsContent contentList={contentList} handleRemoveClick={(index) => this.handleRemoveClick(index)} />
        {/*  goodsList.length && goodsList[index] */}
        {/* <GoodsName /> */}
      </div>
    )
  }
}
